package org.example.l0;

import org.example.leetcpde.IListNode;
import org.junit.jupiter.api.Test;

public class rotateRight implements IListNode {

    @Test
    void run() {
        ListNode fill = new ListNode().fill("[1,2,3,4,5]");
        rotateRight(fill, 2);
    }

    public ListNode rotateRight(ListNode head,
                                int k) {
        if (head == null || head.next == null || k == 0) {
            return head;
        }

        ListNode it = head;
        int size = 1;
        for (; it.next != null; size++, it = it.next) {
        }

        int retain = size - k % size;
        if (retain == size) {
            return head;
        }

        it.next = head;
        while (retain-- > 0) {
            it = it.next;
        }

        ListNode newHead = it.next;
        it.next = null;
        return newHead;
    }
}
